<?php
/**
 * Created by PhpStorm.
 * User: 云信
 * Date: 2022/5/11
 * Time: 13:44
 */

namespace App\Services;


use App\Facades\Data;
use App\Helpers\SystemHelper;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class WsService
{
    #企微管家颁发--先用欢乐动物园（找骆冰申请）
    //private $appid='1553243745';
    //private $app_secret='NnTb4vVN6N6A06MtM2';

    #正式--东方驾校appid和secret
    private $appid='1301268217';
    private $app_secret='a1pHGpXDObBEW2RqYk';

    private $access_token_key='ws_access_token';
    private $ws_host='https://open.wshoto.com/openapi';

    public function getAccessToken(){
        $access_token=Cache::get($this->access_token_key);
        if(!$access_token){
            $url=$this->ws_host.'/access_token?appid='.$this->appid.'&app_secret='.$this->app_secret;
            $res=ws_http_request($url);
            if($res['code']==0){
                $access_token=$res['data']['access_token'];
                Cache::put($this->access_token_key,$access_token,now()->addMinutes(1));
            }
        }
        return $access_token;
    }

    public function refreshAccessToken(){
        Cache::forget($this->access_token_key);
        return $this->getAccessToken();
    }

    public function getCustomerList(){
        $access_token=$this->getAccessToken();
        $url=$this->ws_host.'/customer/info/list?access_token='.$access_token;
        $param=[
            'current_index'=>1,
            'page_size'=>10
        ];
        $res=ws_http_request($url,'POST',$param);
        var_dump($res);exit;
    }

    /**
     * @param $external_userid
     * @return bool
     * 返回逗号分隔的备注手机号
     */
    public function getMobile($external_userid,$userid){
        $access_token=$this->getAccessToken();
        Log::info('userid is:'.$userid);
        $url=$this->ws_host.'/customer/info/detail?access_token='.$access_token.'&external_userid='.$external_userid;
        $res=ws_http_request($url);
        #token过期处理
        if($res==='access_token limit'){
            Log::alert('access_token limit');
            $access_token=$this->refreshAccessToken();
            $url=$this->ws_host.'/customer/info/detail?access_token='.$access_token.'&external_userid='.$external_userid;
            $res=ws_http_request($url);
        }
        $remark_mobiles='';
        if(!empty($res['data']['follow_user'])){
            foreach($res['data']['follow_user'] as $item){
                Log::info('follow_user user_id is:'.$item['userid']);
                if($item['userid']==$userid){
                    $remark_mobiles=is_null($item['remark_mobiles'])?'':$item['remark_mobiles'];
                }
            }
        }
        return $remark_mobiles;
    }
}